<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="btnText">文本框</button>
    <button id="btnBox">复选框</button>
    <button>单选框</button>
    <button>下拉框</button>
    <button>文本域</button>
    <div id="con"></div>
    <button id="sub">提交</button>
  </body>
  <script>
    var textNum = 1
    window.onload = function () {
      document.getElementById('set1').addEventListener('change', function () {
        console.log(this.value)
      })
      //文本框
      btnText.onclick = function () {
        var textObj = document.createElement('input')
        var divObj = document.createElement('div')
        var spanObj = document.createElement('span')
        spanObj.innerHTML = '文本框' + textNum++ + ':'
        divObj.appendChild(spanObj)
        divObj.appendChild(textObj)
        document.getElementById('con').appendChild(divObj)
      }
      //复选框
      btnBox.onclick = function () {
        var checkboxObj = document.createElement('input')
        checkboxObj.type = 'checkbox'
        var divObj = document.createElement('div')
        var spanObj = document.createElement('span')
        spanObj.innerHTML = '复选框' + textNum++ + ':'
        divObj.appendChild(spanObj)
        divObj.appendChild(checkboxObj)
        document.getElementById('con').appendChild(divObj)
      }
      sub.onclick = function () {
        var inp = document.getElementsByTagName('input')
        for (let i = 0; i < inp.length; i++) {
          if (inp[i].type == 'checkbox') {
            console.log(
              inp[i].previousElementSibling.innerHTML +
                '的值为' +
                inp[i].checked
            )
          }
          if (inp[i].type == 'text') {
            console.log(
              inp[i].previousElementSibling.innerHTML + '的值为' + inp[i].value
            )
          }
        }
      }
    }
  </script>
</html>
